package com.glsc.ngateway.platform.service.webfield;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.webfield.FlowFormWebField;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.webfield.WebFieldItem;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.webfield.FlowFormWebFieldRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.webfield.WebFieldItemRepository;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.glsc.ngateway.common.api.common.enums.PlatformConstant.WEB_FLOW_PAGE_TYPE;

/**
 * @author zhengyr
 * @date 2024/2/2-9:42
 */
@Service
public class FlowFormWebFieldService {

    @Resource
    FlowFormWebFieldRepository flowWebFieldRepository;
    @Resource
    WebFieldItemRepository webFieldItemRepository;

    /**
     * 查询流程类页面配置分页
     * @param pageNo
     * @param pageSize
     * @param flowName
     * @return
     */
    public Page<FlowFormWebField> queryFlowFormWebFieldPage(int pageNo, int pageSize, String flowName){
        pageNo= PageUtil.initPageNo(pageNo);
        pageSize=PageUtil.initPageSize(pageSize);
        String sort = "id";
        Sort.Direction direction = Sort.Direction.DESC;
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        return flowWebFieldRepository.page(pageable,flowName);
    }

    /**
     * 根据id查询流程类页面配置
     * @param id
     * @return
     */
    public FlowFormWebField queryFlowFormWebFieldById(Integer id){
        Optional<FlowFormWebField> optional = flowWebFieldRepository.findById(id);
        if (optional.isPresent()) {
            FlowFormWebField flowFormWebField = optional.get();
            String mainKey = flowFormWebField.getProcessDefineKey();
            List<WebFieldItem> allByMainKey = webFieldItemRepository.findAllByMainKey(mainKey);
            Map<String, List<WebFieldItem>> collectMap =allByMainKey.stream().collect(Collectors.groupingBy(h->Objects.isNull(h.getParentFieldCode())?"":h.getParentFieldCode()));
            collectMap.entrySet().stream().forEach(
                    item->item.getValue().stream().forEach(
                            h->  h.setEditFieldList(collectMap.get(h.getFieldCode()))
                    ));

            flowFormWebField.setFieldList(collectMap.get(""));
            return flowFormWebField;
        }
        throw PlatformException.error("未查询到配置数据，请输入正确的配置ident");
    }

    /**
     * 添加/修改流程类配置
     */
    @Transactional(rollbackFor = Exception.class)
    public String addOrUpdateFlowFormWebField(FlowFormWebField params){
        ArrayList<WebFieldItem> resultList = new ArrayList<>();
        if(Objects.nonNull(params.getFieldList())){
            params.getFieldList().stream().forEach(h-> {
                h.setMainKey(params.getProcessDefineKey());
                if(CollectionUtil.isNotEmpty(h.getEditFieldList())){
                    h.getEditFieldList().stream().forEach(i->{
                        i.setMainKey(params.getProcessDefineKey());
                        i.setParentFieldCode(h.getFieldCode());
                    });
                    resultList.addAll(h.getEditFieldList());
                }
            });
            resultList.addAll(params.getFieldList());
        }
        webFieldItemRepository.deleteAllByMainKey(params.getProcessDefineKey());
        webFieldItemRepository.saveAll(resultList);
        FlowFormWebField save = flowWebFieldRepository.save(params);
        Integer id = save.getId();
        save.setIdent(WEB_FLOW_PAGE_TYPE+id);
        return WEB_FLOW_PAGE_TYPE+id;
    }


    /**
     * 删除流程类配置
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteFlowFormWebField (FlowFormWebField param){
        flowWebFieldRepository.deleteById(param.getId());
        webFieldItemRepository.deleteAllByMainKey(param.getProcessDefineKey());
    }

}
